<template>
  <div class="search-result">
    <h5>搜索结果</h5>
    <Best v-show="this.bestbox.artist" :best="best" :songlist="showSong"></Best>
    <div v-if="searchList.length > 0" class="box">
      <!-- 调用song-list组件. 绑定自定义事件play 并继续触发当前组件SearchResult上的play事件 -->
      <SongList
        @play="$emit('play', $event)"
        :keyword="keywords"
        :songlist="showSong"
      ></SongList>
      <!-- 触底下滑 -->
      <div
        v-show="showSong.length > 0"
        class="more"
        @click="loadMore"
        ref="more"
      >
        {{ page >= 10 ? "没有更多了" : "点击加载" }}
      </div>
    </div>
    <!-- 搜索不到结果触发"暂无相关结果" -->
    <div v-else-if="!searchList">
      {{ !this.searchList ? "暂无相关结果" : "" }}
    </div>
  </div>
</template>
<script>

import Best from '@/components/Best.vue'
import SongList from "@/components/SongList.vue";
export default {
  components: {SongList,Best},
  props: {
    keywords: [String, Number, Boolean],
  },
  data() {
    return {
      // 音乐歌曲
      searchList: [],
      bestbox:[],
      best:[],
      page: 1,
    };
  },
  created() {
    this.getResult();
    this.getBest();
    window.addEventListener("scroll", this.scrollbar);
  },
  beforeDestroy() {
    window.removeEventListener("scroll", this.scrollbar); //离开当前路由移除scroll事件
  },
  methods: {
    // 音乐歌曲
    async getResult() {
      let re = await this.axios.get(`/cloudsearch?keywords=${this.keywords}&limit=100&offset=30`);
      if (re && re.result.songCount < 1) {
        this.searchList = false;
        return;
      }
      let slist = re.result.songs.map((item) => {
        item.song = {
          artists: item.ar,
          album: item.al,
          privilege: item.privilege,
        };
        return item;
      });
      this.searchList = slist;
    },
    async getBest(){
      let re = await this.axios.get(`/search/multimatch?keywords=${this.keywords}`);
      this.bestbox = re.result
      if (re.result.artist) {
        this.best = this.bestbox.artist;
      }
      console.log("精准匹配==>", this.best);
    },
    // 点击下一页
    loadMore(){
      if(this.page>=10){
        return;
      }
      this.page++;//下一页
    },
    scrollbar() {
      let el = document.documentElement || document.body; //获取滚动条滚动距离兼容写法
      let top = el.scrollTop + el.clientHeight; //底部距离顶部的距离
      let moretop = this.$refs.more.offsetTop; //more加载条的距离顶部的距离 offsetTop
      console.log("moretop===>",moretop);
      if (top >= moretop + 20) {
        this.loadMore();
      }
    },
  },
  computed:{
    // 点击下一页页数
    showSong(){
      return this.searchList.slice(0,20*this.page);
    }
  },
};
</script>

<style lang="less" scoped>
.search-result {
  padding: 0px 8px;
  h5 {
    font-size: 12px;
    color: #666;
  }
  .box{
    .more{
    text-align: center;
    line-height: 40px;
    font-size:13px;
    color:#666;
  }
  }
}
</style>